'use strict'

import axios from 'axios'
import qs from 'qs'

const BASE_URL = 'http://192.168.1.101:8080/';
const REQ_FAIL_CODE = -404;

axios.interceptors.request.use(config => {
	// loading
	return config
}, error => {
	return Promise.reject(error)
})

axios.interceptors.response.use(response => {
	return response
}, error => {
	return Promise.resolve(error.response)
})

function checkStatus(response) {
	// loading
	if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
		return response
	}
	return {
		status : REQ_FAIL_CODE,
		msg : 'error raised.'
	}
}

function checkCode(res) {
	if (res.status === REQ_FAIL_CODE) {
		alert(res.msg)
	}
	return res
}

export default{
	post(url, data) {
		return axios({
			method : 'post',
			baseURL : BASE_URL,
			url,
			data : qs.stringify(data),
			timeout : 10000,
			headers : {
				'X-Requested-With' : 'XMLHttpRequest',
				'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
			}
		}).then(
			(response) => {
			return checkStatus(response)
		}).then(
			(res) => {
			return checkCode(res)
		})
	},
	get(url, params) {
		return axios({
			method : 'get',
			baseURL : BASE_URL,
			url,
			params,
			timeout : 10000,
			headers : {
				'X-Requested-With' : 'XMLHttpRequest'
			}
		}).then(
			(response) => {
			return checkStatus(response)
		}).then(
			(res) => {
			return checkCode(res)
		})
	}
}
